import io.javalin.Javalin;
import io.javalin.http.staticfiles.Location;
import controller.*;
import util.DatabaseUtil;
import util.FileStorageUtil;
import util.JwtUtil;
import java.io.IOException;
import java.util.HashMap;

public class Main {
    public static void main(String[] args) throws Exception {
        // 初始化文件存储结构
        try {
            FileStorageUtil.initStorageStructure();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件存储初始化失败", e);
        }

        // 创建应用
        Javalin app = Javalin.create(config -> {
            // 静态文件配置
            config.addStaticFiles(staticFiles -> {
                staticFiles.directory = ".";  // 使用当前目录
                staticFiles.location = Location.EXTERNAL;
                staticFiles.hostedPath = "/";  // 映射到根路径
                // 添加 CORS 配置
                staticFiles.precompress = false;  // 禁用预压缩
                staticFiles.headers = new HashMap<String, String>() {{
                    put("Access-Control-Allow-Origin", "*");
                    put("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS");
                    put("Access-Control-Allow-Headers", "Range, Origin");
                    put("Access-Control-Expose-Headers", "Content-Range, Accept-Ranges, Content-Length");
                    put("Cache-Control", "no-cache");  // 禁用缓存，确保实时响应
                }};
            });
            
            // 全局 CORS 配置
            config.enableCorsForAllOrigins();
            config.enableDevLogging();
            
            // CORS 请求处理
            config.accessManager((handler, ctx, permittedRoles) -> {
                // 处理 OPTIONS 请求
                if (ctx.method().equals("OPTIONS")) {
                    ctx.header("Access-Control-Allow-Origin", "*");
                    ctx.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                    ctx.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
                    ctx.header("Access-Control-Max-Age", "86400");
                    ctx.status(200);
                    return;
                }
                handler.handle(ctx);
            });
            
            // 添加请求日志
            config.requestLogger((ctx, ms) -> {
                System.out.println("\n=== 请求开始: " + ctx.path() + " ===");
                System.out.println("请求方法: " + ctx.method());
                
                // 获取并打印用户登录状态
                String token = ctx.header("Authorization");
                if (token != null && token.startsWith("Bearer ")) {
                    token = token.substring(7);
                    try {
                        Long userId = JwtUtil.getUserIdFromToken(token);
                        String username = JwtUtil.getUsernameFromToken(token);
                        System.out.println("登录状态: 已登录 (用户ID: " + userId + ", 用户名: " + username + ")");
                    } catch (Exception e) {
                        System.out.println("登录状态: Token无效");
                    }
                } else {
                    System.out.println("登录状态: 未登录");
                }
            });
        }).start(4000);

        // 用户相关路由
        app.get("/api/user/info", UserController::getUserInfo);
        app.post("/api/user/register", UserController::register);
        app.post("/api/user/login", UserController::login);
        app.post("/api/user/background", UserController::uploadBackground);
        app.post("/api/user/background-color", UserController::updateUserBackgroundColor);
        
        // 音乐相关路由 - 固定路径
        app.get("/api/music/search", MusicController::searchMusic);
        app.get("/api/music/suggestions", MusicController::getSuggestions);
        app.get("/api/music/hot", MusicController::getHotMusic);
        app.get("/api/music/library", MusicController::getMusicLibrary);
        app.get("/api/music/recent-music", MusicController::getRecentPlays);
        app.get("/api/music/playlist", MusicController::getCurrentPlaylist);
        app.delete("/api/music/playlist/clear", MusicController::clearPlaylist);

        // 音乐相关路由 - ID
        app.get("/api/music/{id}/cover", MusicController::getMusicCover);
        app.get("/api/music/{id}/lyric", MusicController::getMusicLyric);
        app.get("/api/music/{id}/source", MusicController::getMusicSource);
        app.get("/api/music/{id}", MusicController::getMusicById);
        app.post("/api/music/{id}/play", MusicController::addToRecentPlays);
        app.post("/api/music/{id}/play-count", MusicController::updatePlayCount);

        // 音乐相关路由 - 播放列表
        app.post("/api/music/playlist/add", MusicController::addToPlaylist);
        app.post("/api/music/playlist/remove", MusicController::removeFromPlaylist);
        
        // 歌单相关路由
        app.get("/api/user/playlists", PlaylistController::getUserPlaylists);
        app.get("/api/user/favorites", PlaylistController::getFavoritePlaylists);
        app.get("/api/playlist/hot", PlaylistController::getHotPlaylists);
        app.get("/api/playlist/{id}", PlaylistController::getPlaylistInfo);
        app.get("/api/playlist/full/{id}", PlaylistController::getFullPlaylist);

        app.post("/api/playlist/create", PlaylistController::createPlaylist);
        app.post("/api/playlist/add-songs", PlaylistController::addSongsToPlaylists);
        app.post("/api/playlist/{id}/unfavorite", PlaylistController::unfavoritePlaylist);
        app.post("/api/playlist/{id}/favorite", PlaylistController::favoritePlaylist);
        app.post("/api/playlist/{id}/add-to-queue", PlaylistController::addPlaylistToQueue);

        app.put("/api/playlist/{id}/name", PlaylistController::updatePlaylistName);
        app.put("/api/playlist/{id}/description", PlaylistController::updatePlaylistDescription);
        app.put("/api/playlist/{id}/cover", PlaylistController::updatePlaylistCover);

        app.delete("/api/playlist/{id}/songs", PlaylistController::removeSongsFromPlaylist);
        app.delete("/api/playlist/{id}", PlaylistController::deletePlaylist);
        
        // 资源相关路由
        app.get("/api/resource/my-music", ResourceController::getUserMusics);
        app.post("/api/resource/upload-music", ResourceController::uploadMusic);
        app.delete("/api/resource/{id}", ResourceController::deleteMusic);
        
        // 关闭数据库连接
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            DatabaseUtil.closeConnection();
        }));
    }
}